package com.bckj.fastboot.iot.parse.core;

import com.bckj.fastboot.iot.common.entity.IotProtocolItem;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * StandardProtocolParser
 *
 * @author wfc
 **/
@Component
public class StandardProtocolParser extends AbstractProtocolParser {
    @Override
    public void parse(Object protocolData, String devCode, Object... extra) {
        byte[] bytes = (byte[]) protocolData;
        int category = bytes[2];
        int type = bytes[3];
        int cmd = bytes[4];
        // 校验和
        int length = bytes[5];
        byte[] data = new byte[length];
        System.arraycopy(bytes, 5, data, 0, length);
        String protocolCode = "%02d%02d".formatted(category, type);
        String cmdCode = "%02d".formatted(cmd);
        List<IotProtocolItem> protocolItemList = getProtocolItemList(protocolCode, cmdCode);
        Map<String, Object> dataMap = parseData(data, protocolItemList);
        var context = ProtocolParseContext.of(devCode, protocolCode, cmdCode, dataMap);
        switch (cmd) {
            // 心跳
            case 0x01 -> {
                handleHeartbeat(context);
            }
            // 基础
            case 0x02 -> {
                var request = buildBasicData(context);
                handleBasicData(request);
                triggerAlarm(context);
            }
            // 报警
            case 0x03 -> {
                var request = buildAlarmData(context);
                handleAlarmData(request);
            }
            // 状态
            case 0x04 -> {
                var request = buildStatusData(context);
                handleStatusData(request);
                triggerAlarm(context);
            }
            // 事件
            case 0x05 -> {
                triggerAlarm(context);
            }
        }
    }
}
